package org.misty.seckill.controller;

import org.misty.seckill.interceptor.AuthorizationInterceptor2;
import org.misty.seckill.service.LoginService;
import org.misty.seckill.util.ServletUtil;
import org.misty.seckill.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

@RestController
@RequestMapping("/login")
@AuthorizationInterceptor2.IgnoreAuth
public class LoginController {
  @Autowired
  private LoginService loginService;

  @PostMapping(value = "", consumes = MediaType.APPLICATION_JSON_VALUE)
  public boolean jsonLogin(@RequestBody @Valid LoginVo vo, HttpServletRequest request, HttpServletResponse response) throws IOException {
    var redirectToken = ServletUtil.readSessionToken(request);
    var redirectUri = loginService.getRedirectByToken(redirectToken);
    var retVo = loginService.login(vo);
    ServletUtil.writeSessionToken(response, retVo.getSessionToken(), retVo.getSessionExpiry(), "/");
    if (!StringUtils.isEmpty(redirectUri)) {
      if (ServletUtil.isAjaxRequest(request)) {
        response.addHeader("S_REDIRECT_URI", redirectUri);
      } else {
        response.sendRedirect(redirectUri);
      }
      loginService.clearRedirect(redirectToken);
    }
    return true;
  }

  @PostMapping(value = "", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
  public boolean formLogin(@Valid LoginVo vo, HttpServletRequest request, HttpServletResponse response) throws IOException {
    return this.jsonLogin(vo, request, response);
  }
}
